﻿using AllWayNet.Logger;
using DemoServiceLibrary;
using ServerUtils;
using System;

namespace DemoServer
{
    public class Server : IDisposable
    {
        private ServiceHostEx<ServerInfoService> serverInfoServiceHost;
        private bool disposed = false;

        public Server(IServerInfoProvider serverInfoProvider)
        {
            ServerInfoService serverInfoService = new ServerInfoService(serverInfoProvider);
            serverInfoService.Log += this.ServerInfoServiceLog;
            serverInfoService.LogOperations = true;

            this.serverInfoServiceHost = new ServiceHostEx<ServerInfoService>(serverInfoService);
            this.serverInfoServiceHost.Log += this.ServerInfoServiceHostLog;
        }

        private void ServerInfoServiceLog(object sender, ServerUtils.LogEventArgs e)
        {
            ApplicationLogger.Log(e.Type, e.Message);
        }

        private void ServerInfoServiceHostLog(object sender, LogEventArgs e)
        {
            ApplicationLogger.Log(e.Type, e.Message);
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Start()
        {
            this.serverInfoServiceHost.Open();
        }

        public void Stop()
        {
            this.serverInfoServiceHost.Close();
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                this.Stop();
            }

            disposed = true;
        }
    }
}
